<?php
/**
 * Created by PhpStorm.
 * User: roy
 * Date: 2017/9/21
 * Time: 19:47
 */
namespace app\Console;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\platform\controller\Index;
use think\swoole;

class WebSocket extends Command
{
    // Server 实例
    public $server;

    protected function configure()
    {
        $this->setName('websocket:start')->setDescription('Start Web Socket Server!');
    }

    protected function execute(Input $input, Output $output)
    {
        // 监听所有地址，监听 9527 端口
        $this->server = new \swoole_websocket_server('0.0.0.0', 9527);

        // 设置 server 运行前各项参数
        // 调试的时候把守护进程关闭，部署到生产环境时再把注释取消
         $this->server->set([
             'daemonize' => false,
         ]);


        // 设置回调函数
        $this->server->on('Open', [$this, 'onOpen']);
        $this->server->on('Message', [$this, 'onMessage']);
        $this->server->on('Close', [$this, 'onClose']);
        $this->server->on('Close', [$this, 'onClose']);

        $this->server->start();
        $output->writeln("WebSocket: Start.\n");
    }


    // 建立连接时回调函数
    public function onOpen(\swoole_websocket_server $server, \swoole_http_request $request)
    {
        echo "server: handshake success with fd{$request->fd}\n";

        file_put_contents( __DIR__ .'/log.txt' , $request->fd);
    }

    // 收到数据时回调函数
    public function onMessage(\swoole_websocket_server $server, \swoole_websocket_frame $frame)
    {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        //$server->push($frame->fd, "this is server:{$frame->data}");
        $this->pushMessage($server,$frame);
    }

    // 连接关闭时回调函数
    public function onClose($server, $fd)
    {
        echo "client {$fd} closed\n";
    }

    //消息推送
    function pushMessage($ws,$frame){
        $data = $frame->data;
        $msg = file_get_contents( __DIR__ .'/log.txt');
        for ($i=1 ; $i<= $msg ; $i++) {
            $ws->push($i, $frame->fd.' : '.$data);
        }
    }
}